import open3d as o3d
import numpy as np

ply_point_cloud_path = r"D:\AllCode\3D Point Cloud\Open3D\Notes\Part 2 Voxel downsampling\Try\bun_zipper.ply"
pcd = o3d.io.read_point_cloud(ply_point_cloud_path)

print("斯坦福兔子基本信息")
print(pcd)
print(np.asarray(pcd.points))

# 体素下采集
voxel_size = 0.01
print(f"体素下采集斯坦福兔子：体素边长为{voxel_size}")
downpcd = pcd.voxel_down_sample(voxel_size = voxel_size)

# 方法一验证
# print(downpcd)
# o3d.visualization.draw_geometries([downpcd])

# 方法二验证
# pcd.paint_uniform_color([0,0,0])      #原始点云改成黑色
# downpcd.paint_uniform_color([0,1,0])  #体素下采样后的数据设置成绿色
# o3d.visualization.draw_geometries([pcd,downpcd])

#方法三验证
import time

def setup_vis(pcd_to_show,window_name):
    vis = o3d.visualization.Visualizer()
    vis.create_window(window_name = window_name, width = 1000, height = 800)
    vis.add_geometry(pcd_to_show)
    return vis

vis_pcd = setup_vis(pcd,"原始点云")
vis_downpcd = setup_vis(downpcd,f"边长为{voxel_size}的体素下采样点云")

try:
    pcd_running = True
    downpcd_running = True
    while pcd_running and downpcd_running:
        if pcd_running: 
            pcd_running= vis_pcd.poll_events()
        if downpcd_running:
            downpcd_running = vis_downpcd.poll_events()
            vis_downpcd.update_renderer()
        
        time.sleep(0.01)
except KeyboardInterrupt:
    pass
finally:
    vis_downpcd.destroy_window()
    vis_pcd.destroy_window()